package com.southminority.ethnic.controller.admin.organization;

import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.pojo.otherPojo.Organization;
import com.southminority.ethnic.service.organization.OrganizationService;
import com.southminority.ethnic.controller.organization.vo.OrganizationVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 机构组织管理后台控制器
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "13 - 机构组织管理API", description = "【后台】机构组织的增删改查接口")
@RestController
@RequestMapping("/admin/organization")
@CrossOrigin
public class OrganizationAdminController {

    private final OrganizationService organizationService;

    public OrganizationAdminController(OrganizationService organizationService) {
        this.organizationService = organizationService;
    }

    @GetMapping("/page")
    @Operation(summary = "分页和条件查询机构", description = "后台管理使用的机构列表接口，支持多种条件筛选和分页。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    public R<PageResult<OrganizationVO>> getOrganizationPage(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页显示数量", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "关键词（名称）", example = "实验室") @RequestParam(required = false) String keyword,
            @Parameter(description = "机构类型", example = "省级文科实验室") @RequestParam(required = false) String organizationType,
            @Parameter(description = "状态", example = "1", schema = @Schema(description = "1-启用, 0-禁用", type = "integer", allowableValues = {"1", "0"})) @RequestParam(required = false) Integer status) {
        try {
            PageResult<OrganizationVO> pageResult = organizationService.getOrganizationPageForAdmin(page, size, keyword, organizationType, status);
            return R.ok(pageResult);
        } catch (Exception e) {
            log.error("分页查询机构失败", e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "获取单个机构的详细信息（用于编辑）", description = "根据机构ID查询，返回其完整信息，包括被禁用的机构。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "机构不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<OrganizationVO> getOrganizationDetail(@Parameter(description = "机构的唯一ID", example = "1", required = true) @PathVariable Long id) {
        try {
            OrganizationVO organizationVO = organizationService.getOrganizationDetailForAdmin(id);
            return R.ok(organizationVO);
        } catch (Exception e) {
            log.error("获取机构详情失败", e);
            return R.fail("获取详情失败: " + e.getMessage());
        }
    }

    @PostMapping("/create")
    @Operation(summary = "新增一个机构", description = "传入机构的完整信息（除ID外）来创建一个新的记录。注意：JSON字段应为字符串格式。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功，返回创建后的机构信息"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<OrganizationVO> createOrganization(@RequestBody(description = "机构信息的JSON对象", required = true,
            content = @Content(schema = @Schema(implementation = Organization.class)))
            @org.springframework.web.bind.annotation.RequestBody Organization organization) {
        try {
            log.info("管理员创建机构: {}", organization.getName());
            OrganizationVO result = organizationService.createOrganization(organization);
            return R.ok(result);
        } catch (Exception e) {
            log.error("创建机构失败", e);
            return R.fail("创建失败: " + e.getMessage());
        }
    }

    @PutMapping("/update/{id}")
    @Operation(summary = "根据ID更新机构信息", description = "提供机构的ID和更新后的信息，对现有记录进行修改。注意：JSON字段应为字符串格式。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功，返回更新后的机构信息"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "404", description = "机构不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<OrganizationVO> updateOrganization(
            @Parameter(description = "要更新的机构ID", example = "1", required = true) @PathVariable Long id,
            @RequestBody(description = "包含更新字段的机构JSON对象", required = true,
                    content = @Content(schema = @Schema(implementation = Organization.class)))
            @org.springframework.web.bind.annotation.RequestBody Organization organization) {
        try {
            log.info("管理员更新机构: ID={}, Name={}", id, organization.getName());
            OrganizationVO result = organizationService.updateOrganization(id, organization);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新机构失败", e);
            return R.fail("更新失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "根据ID逻辑删除机构", description = "将指定ID的机构状态设置为-1（已删除），并非物理删除。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "机构不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> deleteOrganization(@Parameter(description = "要删除的机构ID", example = "1", required = true) @PathVariable Long id) {
        try {
            log.info("管理员删除机构: ID={}", id);
            boolean result = organizationService.deleteOrganization(id);
            return R.ok(result);
        } catch (Exception e) {
            log.error("删除机构失败", e);
            return R.fail("删除失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量逻辑删除机构", description = "传入一个ID列表，批量将对应的机构状态设置为-1。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "批量删除成功"),
            @ApiResponse(responseCode = "400", description = "ID列表为空"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> batchDeleteOrganization(@RequestBody(description = "包含多个机构ID的数组", required = true,
            content = @Content(schema = @Schema(type = "array", implementation = Long.class)))
            @org.springframework.web.bind.annotation.RequestBody List<Long> ids) {
        try {
            log.info("管理员批量删除机构: IDs={}", ids);
            boolean result = organizationService.batchDeleteOrganizations(ids);
            return R.ok(result);
        } catch (Exception e) {
            log.error("批量删除机构失败", e);
            return R.fail("批量删除失败: " + e.getMessage());
        }
    }

    @PutMapping("/status/{id}")
    @Operation(summary = "更新机构状态", description = "更新单个机构的状态，如启用（1）和禁用（0）。")
    @Parameters({
            @Parameter(name = "id", description = "机构ID", example = "1", required = true),
            @Parameter(name = "status", description = "新的状态值", example = "0", required = true,
                    schema = @Schema(description = "1-启用, 0-禁用", type = "integer", allowableValues = {"1", "0"}))
    })
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "状态更新成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "404", description = "机构不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> updateOrganizationStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        try {
            log.info("管理员更新机构状态: ID={}, Status={}", id, status);
            boolean result = organizationService.updateOrganizationStatus(id, status);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新机构状态失败", e);
            return R.fail("更新状态失败: " + e.getMessage());
        }
    }

    @PutMapping("/featured/{id}")
    @Operation(summary = "设置首页展示", description = "设置或取消某个机构的首页展示")
    @Parameters({
            @Parameter(name = "id", description = "机构ID", example = "1", required = true),
            @Parameter(name = "isFeatured", description = "是否首页展示：1-是，0-否", example = "1", required = true,
                    schema = @Schema(allowableValues = {"1", "0"}))
    })
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "设置成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "404", description = "机构不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> setOrganizationFeatured(
            @PathVariable Long id,
            @RequestParam Integer isFeatured) {
        try {
            log.info("管理员设置机构首页展示: ID={}, IsFeatured={}", id, isFeatured);
            boolean result = organizationService.setOrganizationFeatured(id, isFeatured);
            return R.ok(result);
        } catch (Exception e) {
            log.error("设置机构首页展示失败", e);
            return R.fail("设置首页展示失败: " + e.getMessage());
        }
    }

    @PutMapping("/team-display/{id}")
    @Operation(summary = "设置机构团队页展示开关", description = "设置或取消机构在团队动态页的展示开关。display=1 表示展示，display=0 表示不展示。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "设置成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> setOrganizationTeamDisplay(
            @Parameter(description = "机构ID", required = true) @PathVariable Long id,
            @Parameter(description = "是否展示（1-是，0-否）", required = true, schema = @Schema(allowableValues = {"1","0"})) @RequestParam Integer display) {
        boolean ok = organizationService.setOrganizationTeamDisplay(id, display);
        return ok ? R.ok(true) : R.fail("设置团队展示失败");
    }

    @GetMapping("/test")
    @Operation(summary = "测试接口连通性", description = "一个简单的GET请求，用于检查服务是否正常运行。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "服务正常")
    })
    public R<String> test() {
        return R.ok("机构组织管理服务正常");
    }
} 
